package org.game.netty.session;

import java.net.SocketAddress;

import org.game.actor.msg.InternalMsg;
import org.game.constant.SessionConstent;
import org.game.db.bean.Player;
import org.game.manager.PlayerManager;

import com.sojoys.artifact.constant.SessionStatusEnum;
import com.sojoys.artifact.core.IServer;
import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.factory.session.ISession;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

import akka.actor.ActorRef;
import io.netty.channel.Channel;
import io.netty.util.Attribute;

public class NettySession extends ISession {

	static Log log = LogFactory.get(NettySession.class);
	
	protected Channel channel;
	
	public NettySession(Channel channel) {
		super();
		this.channel = channel;
	}

	// ----------------------------------------
	@Override
	public String getId() {
		return channel.id().asShortText();
	}

	@Override
	public SocketAddress localAddress() {
		return channel.localAddress();
	}

	@Override
	public SocketAddress remoteAddress() {
		return channel.remoteAddress();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Channel getChannel() {
		// TODO Auto-generated method stub
		return channel;
	}

	@Override
	public void setChannel(Object channel) {
		this.channel = (Channel) channel;
	}

	@Override
	public void close() {
		if(getStatus() == SessionStatusEnum.RUNNING){
			// 执行下线操作
			Player player = getAttr(SessionConstent.PLAYER);
			if (player != null && player.getPlayerProxy().isOnline()) {
				player.getPlayerProxy().getActorRef().tell(new InternalMsg("offline", null), ActorRef.noSender());
			}
			setStatus(SessionStatusEnum.CLOSE);
		}
	}

	@Override
	public boolean isWritable() {
		return channel.isWritable();
	}

	@Override
	public boolean isOpen() {
		return channel.isOpen();
	}

	@Override
	public boolean isActive() {
		return channel.isActive();
	}

	@Override
	protected void writeAndFlush(IMessage msg) {
		if(IServer.getConstants().isDevMode()){
			log.debug("Push Msg sessionId:{} {}",getId(),msg.toString());		
		} 
		channel.writeAndFlush(msg);
	}
}
